package com.centling.smartSealForPhone.application;

import android.app.Application;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.util.DisplayMetrics;

import com.centling.smartSealForPhone.BuildConfig;
import com.centling.smartSealForPhone.constants.SPConstants;
import com.centling.smartSealForPhone.constants.UrlConstants;
import com.centling.smartSealForPhone.utils.CrashHandler;
import com.centling.smartSealForPhone.utils.SPUtil;
import com.example.localalbum.common.LocalImageHelper;
import com.wsdk.Wsdk;
import com.wsdk.WsdkConfig;
import com.wsdk.exception.WsdkException;

/**
 * @author fionera
 */
public class SmartSeal
        extends Application {

    public static int screenWidth;
    public static int screenHeight;
    public static float screenDensity;
    public static float scaledDensity;
    private static SmartSeal application;

    public static SmartSeal getInstance() {
        return application;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        application = this;
        getDisplayMetrics();

        LocalImageHelper.init(application);

        if (!BuildConfig.DEBUG) {
            CrashHandler crashHandler = CrashHandler.getInstance();
            crashHandler.init(getApplicationContext());
        }

        changeIp("http://192.168.102.136:34880");

        /*
            use wsdk to inject root url
         */
        WsdkConfig.Builder wsdkConfigBuilder = new WsdkConfig.Builder();
        try {
            Wsdk.init(this, wsdkConfigBuilder.setRootUrl(getIp()).build());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getDisplayMetrics() {
        DisplayMetrics metric = getApplicationContext().getResources().getDisplayMetrics();
        screenWidth = metric.widthPixels;
        screenHeight = metric.heightPixels;
        screenDensity = metric.density;
        scaledDensity = metric.scaledDensity;
    }

    public String getIp() {
        return SPUtil.getString(SPConstants.IPADDRESS);
    }

    /**
     * 将新的ip存入 sharedPreference，进行共享数据
     * @param ip need save ip
     */
    public void changeIp(String ip) {
        SPUtil.setString(SPConstants.IPADDRESS, ip);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        // 非默认值
        if (newConfig.fontScale != 1) {
            getResources();
        }
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        // 非默认值
        if (res.getConfiguration().fontScale != 1) {
            Configuration newConfig = res.getConfiguration();
            newConfig.fontScale = 1;
            super.createConfigurationContext(newConfig);
        }
        return res;
    }
}

